package man4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Vector;

import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

public class TaskStore {	
	public static Vector loadTasks(String name) {
		try {
			RecordStore rs = RecordStore.openRecordStore(name, true, RecordStore.AUTHMODE_PRIVATE, true);
							
			RecordEnumeration en = rs.enumerateRecords(null, new RecordComparator() {
				public int compare(byte[] rec1, byte[] rec2) {					
					try {
						int pos1 = new DataInputStream(new ByteArrayInputStream(rec1)).readInt();
						int pos2 = new DataInputStream(new ByteArrayInputStream(rec2)).readInt();
						
						return pos1 - pos2;
					} catch (Exception e) {
						throw new RuntimeException(e.getMessage());
					}
				}
			}, false);
			
			Vector tasks = new Vector();
			
			while(en.hasNextElement()) {
				byte[] rec = en.nextRecord();
				
				DataInputStream in = new DataInputStream(new ByteArrayInputStream(rec));
				
				in.readInt();
				String title = in.readUTF();
				boolean complete = in.readBoolean();
				
				tasks.addElement(new Task(title, complete));
			}
			
			rs.closeRecordStore();
			
			return tasks;			
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public static void saveTasks(String name, Vector tasks) {
		try {
			RecordStore.deleteRecordStore(name);
			
			RecordStore rs = RecordStore.openRecordStore(name, true, RecordStore.AUTHMODE_PRIVATE, true);			
			
			for (int i = 0; i < tasks.size(); i++) {
				Task t = (Task) tasks.elementAt(i);
				
				ByteArrayOutputStream baout = new ByteArrayOutputStream();
				DataOutputStream dout = new DataOutputStream(baout);
				
				dout.writeInt(i);
				dout.writeUTF(t.getString());
				dout.writeBoolean(t.isComplete());
				
				byte[] buf = baout.toByteArray();
				
				rs.addRecord(buf, 0, buf.length);
			}
			
			rs.closeRecordStore();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
}
